package com.love.netty.demo.handler.request;

import com.love.netty.core.packet.request.MessageRequestPacket;
import com.love.netty.core.packet.response.MessageResponsePacket;
import com.love.netty.model.Session;
import com.love.netty.util.SessionUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.text.SimpleDateFormat;

/**
 * @ClassName: MessageRequestHandler
 * @Description:
 * @Author: wuj
 * @Date: 2021-06-24 11:46
 **/
@ChannelHandler.Sharable
public class MessageRequestHandler extends SimpleChannelInboundHandler<MessageRequestPacket> {

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    // 2. 构造单例
    public static final MessageRequestHandler INSTANCE = new MessageRequestHandler();

    protected MessageRequestHandler() {
    }


    /**
     * 服务端的功能相当于消息转发：收到一个客户端的消息之后，构建一条发送给另一个客户端的消息，接着拿到另一个客户端的 channel
     *
     * @param channelHandlerContext
     * @param packet
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MessageRequestPacket packet) throws Exception {
        // 1.拿到消息发送方的会话信息
        Session session = SessionUtils.getSession(channelHandlerContext.channel());

        // 2.通过消息发送方的会话信息构造要发送的消息
        MessageResponsePacket messageResponsePacket = new MessageResponsePacket();
        messageResponsePacket.setFromUserId(session.getUserId());
        messageResponsePacket.setFromUserName(session.getUserName());
        messageResponsePacket.setMessage(packet.getMessage());

        // 3.拿到消息接收方的 channel
        Channel toUserChannel = SessionUtils.getChannel(packet.getToUserId());

        // 4.将消息发送给消息接收方
        if (toUserChannel != null && SessionUtils.hasLogin(toUserChannel)) {
            toUserChannel.writeAndFlush(messageResponsePacket);
        } else {
            System.err.println("[" + packet.getToUserId() + "] 不在线，发送失败!");
        }

//        // 处理消息
//        System.out.println(sdf.format(new Date()) + ": 收到客户端消息: " + packet.getMessage());
//        MessageResponsePacket messageResponsePacket = new MessageResponsePacket();
//        messageResponsePacket.setMessage("服务端回复【" + messageResponsePacket.getMessage() + "】");
//        channelHandlerContext.channel().writeAndFlush(packet);
    }
}
